<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container" style="margin-bottom:20px">
      <span style="margin-left:10px">推荐院校：</span>
      <el-input @keyup.enter.native="handleFilter" style="width: 160px;" class="filter-item" placeholder="搜索推荐院校" v-model="listQuery.academyName" clearable></el-input>
      <span style="margin-left:10px">投放地区：</span>
      <el-cascader class="search__input" change-on-select clearable placeholder="全部" expand-trigger="click" :options="areaCascadeOptions" v-model="areaList" />
      <span style="margin-left:10px">投放高中：</span>
      <el-input @keyup.enter.native="handleFilter" style="width: 160px;" class="filter-item" placeholder="搜索投放高中" v-model="listQuery.title" clearable>
      </el-input>
      <span>投放状态：</span>
      <el-select v-model="listQuery.isDelete" clearable placeholder="请选择投放状态">
        <el-option
          v-for="item in deleteOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
      <span>是否全国投放：</span>
      <el-select v-model="listQuery.isNationwide" clearable placeholder="请选择是否全国投放">
        <el-option
          v-for="item in countryOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-plus" @click="handleAddNewRecommend">新增推荐</el-button>
    </div>
    <el-table :key='tableKey' :data="recommendList" v-loading="listLoading" element-loading-text="数据加载中，请稍后" border fit highlight-current-row style="width: 100%">  
      <el-table-column min-width="30" align="center" label="ID" prop="id"></el-table-column> 
      <el-table-column min-width="110" align="center" label="推荐院校">
        <template slot-scope="scope">
          <span>{{ scope.row.academyName }}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="110" align="center" label="投放区域">
        <template slot-scope="scope">
          <span>{{ scope.row.areaName || '/' }}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="110" align="center" label="投放高中" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.title || '/'}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="60" align="center" label="是否全国投放" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.isNationwide == 1 ? '是' : '/'}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="40" align="center" label="权重">
        <template slot-scope="scope">
          <span>{{ scope.row.sort }}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="60" align="center" label="投放状态" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.isDelete == 0 ? '启用' : '禁用'}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="120">
        <template slot-scope="scope">
          <el-button size="small" type="danger" @click="handleOprate(scope.row.id, 1)" v-if="scope.row.isDelete == 0">禁用</el-button>
          <el-button size="small" type="primary" @click="handleOprate(scope.row.id, 0)" v-else>启用</el-button>
          <el-button size="small" type="primary" @click="handleEditData(scope.row.id)" :disabled="scope.row.isDelete == 1">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDeleteData(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div v-show="!listLoading" class="pagination-container">
      <el-pagination 
        @size-change="handleSizeChange" 
        @current-change="handleCurrentChange" 
        :current-page.sync="listQuery.pageNo"
        :page-sizes="[5,10,20,30,50]" 
        :page-size="listQuery.pageSize" 
        layout="total, sizes, prev, pager, next, jumper" 
        :total="total">
      </el-pagination>
    </div>

    <!-- 新增推荐 -->
    <el-dialog width="54%" :title="action == 'new' ? '新增推荐院校' : '编辑推荐院校'" :visible.sync="recommendDialog" class="popBox" :center="true" @close="dialogClosed">
      <div class="create_model">
        <el-form :model="schoolsForm" :rules="rules" ref="schoolsForm" label-width="100px">
          <el-row>  
            <el-col :span="12" v-if="action == 'new'">
              <el-form-item label="推荐院校" prop="academyCode">
                <el-select
                  size="small"
                  v-model="schoolsForm.academyCode"
                  clearable
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请输入关键词"
                  :remote-method="getCollegeOptions">
                  <el-option v-for="item in collegeByTitleOptions" :key="item.academyCode" :label="item.academyName" :value="item.academyCode">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-else>
              <el-form-item label="推荐院校" prop="academyName">
                <el-input type="text" v-model="academyName" disabled placeholder="请选择推荐院校"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="权重" prop="sort">
                <el-input-number v-model="schoolsForm.sort" :min="0" :max="10000" label="请输入商品权重"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="投放类型" prop="putInType">
                <el-radio-group v-model="putInType" @change="handleRadioChange">
                  <el-radio-button label="地区" value="地区"></el-radio-button>
                  <el-radio-button label="全国" value="全国"></el-radio-button>
                  <el-radio-button label="学校" value="学校"></el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-show="putInType == '地区'">
              <el-form-item label="投放区域">
                <el-cascader class="search__input" change-on-select clearable placeholder="全部" expand-trigger="click" :options="areaCascadeOptions" v-model="putInArea" />
              </el-form-item>
            </el-col>
            <el-col :span="12" v-show="putInType == '学校'">
              <el-form-item label="投放高中" v-if="!schoolName || schoolName == ''">
                <el-select
                  size="small"
                  v-model="schoolsForm.schoolId"
                  clearable
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请输入关键词"
                  :remote-method="getHighSchoolOptions">
                  <el-option v-for="item in highSchoolsByTitleOptions" :key="item.schoolId" :label="item.schoolName" :value="item.schoolId">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="投放高中" prop="schoolName" v-else>
                <el-input type="text" v-model="schoolName" placeholder="请选择投放高中" clearable></el-input>
              </el-form-item>

            </el-col>
          </el-row>

          <el-row>  
            <el-col :span="12" :offset="8">
              <el-form-item>
                <el-button type="primary" @click="handleSubmit">{{ action == 'new' ? '提交' : '修改'}}</el-button>
              </el-form-item>
            </el-col>
          </el-row>  
        </el-form>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { mapActions, mapGetters } from 'vuex'
import { getSchoolsByTitle } from '@/api/user'
import { queryLikeSchoolByName } from '@/api/marketer'
import { queryRecommendAcademyByPage,
  updateRecommendStatusById,
  addRecommendAcademy,
  updateRecommendAcademyById,
  queryRecommendAcademyInfoById,
  deleteRecommendAcademyById
} from '@/api/recommend'
export default {
  data() {
    return {
      action: 'new', // 新建院校 --> new    编辑院校 --> modify
      listQuery: {
        academyName: null, // 推荐院校名称
        title: null, // 投放高中
        isDelete: null, // 投放状态  -->  0：启动；1：禁用
        isNationwide: null, // 是否投放全国  -->  1：是；0：否
        provinceId: null, // 省份ID
        cityId: null, // 城市ID
        regionId: null, // 区域ID
        pageNo: 1,
        pageSize: 10
      },
      total: null,
      recommendList: [],
      tableKey: 0,
      listLoading: false,
      areaList: [], // 区域集合 --- 搜索
      putInArea: [], // 区域集合 --- 编辑
      deleteOptions: [ // 投放状态list
        { value: 0, label: '启用' },
        { value: 1, label: '禁用' }
      ],
      countryOptions: [ // 是否投放全国list
        { value: 1, label: '是' },
        { value: 0, label: '否' }
      ],
      recommendDialog: false,
      rules: {
        putInType: [{ required: true, message: '请输入投放类型', trigger: 'blur' }],
        sort: [{ required: true, message: '请输入推荐权重', trigger: 'change' }],
        academyCode: [{ required: true, message: '请选择推荐院校', trigger: 'blur' }]
      },
      putInType: '地区', // 投放类型
      schoolsForm: {
        sort: 100, // 权重
        provinceId: null, // 省份ID
        cityId: null, // 城市ID
        regionId: null, // 区域ID
        schoolId: null, // 投放高中ID
        isNationwide: null, // 是否全国投放
        academyCode: null, // 推荐院校ID
        id: null
      },
      academyName: '',
      schoolName: '',
      highSchoolsByTitleOptions: [],
      collegeByTitleOptions: []

    }
  },
  created() {
    this.GetAreaCascadeOptions()
    this.searchRecommendAcademyList()
  },
  computed: {
    ...mapGetters(['areaCascadeOptions'])
  },
  watch: {
    areaList(arr) {
      this.listQuery.provinceId = arr[0] ? arr[0] : null
      this.listQuery.cityId = arr[1] ? arr[1] : null
      this.listQuery.regionId = arr[2] ? arr[2] : null
    },
    putInArea(arr) {
      this.schoolsForm.provinceId = arr[0] ? arr[0] : null
      this.schoolsForm.cityId = arr[1] ? arr[1] : null
      this.schoolsForm.regionId = arr[2] ? arr[2] : null
    }
  },
  methods: {
    // 映射 Actions
    ...mapActions(['GetAreaCascadeOptions']),

    // 分页查询所有推荐院校及其投放
    searchRecommendAcademyList() {
      this.listLoading = true
      queryRecommendAcademyByPage(this.listQuery).then(res => {
        this.listLoading = false
        if (res.code == 0) {
          this.recommendList = res.data.list
          this.total = res.data.total
        } else {
          this.$message('网络故障，请重新尝试！')
        }
      })
    },

    // 分页
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.searchRecommendAcademyList()
    },
    handleCurrentChange(val) {
      this.listQuery.pageNo = val
      this.searchRecommendAcademyList()
    },

    // 更改投放状态
    handleOprate(id, type) {
      let confirmText = ''
      if (type == 1) {
        confirmText = '是否确认将该院校从推荐列表中清除？'
      } else {
        confirmText = '是否将该院校添加进推荐列表？'
      }
      this.$confirm(confirmText, '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateRecommendStatusById({
          id: id,
          isDelete: type
        }).then(res => {
          if (res.message == '操作成功') {
            this.$message({
              message: res.message,
              type: 'success'
            })
          } else {
            this.$message({
              message: res.message,
              type: 'error'
            })
          }
          this.searchRecommendAcademyList()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '操作已取消'
        })
      })
    },

    handleSubmit() {
      if (!this.schoolsForm.academyCode) {
        this.$message({
          message: '请选择需要推荐的院校',
          type: 'warning'
        })
        return
      }
      if (this.putInType == '地区') {
        if (!this.schoolsForm.provinceId) {
          this.$message({
            message: '请选择指定投放的地区',
            type: 'warning'
          })
          return
        }
      } else if (this.putInType == '学校') {
        if (!this.schoolsForm.schoolId) {
          this.$message({
            message: '请选择指定投放的高中',
            type: 'warning'
          })
          return
        }
      }

      if (this.action == 'new') {
        this.$confirm('是否新增推荐院校信息', '温馨提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 新增
          addRecommendAcademy(this.schoolsForm).then(res => {
            this.recommendDialog = false
            this.searchRecommendAcademyList()
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '操作已取消'
          })
        })
      } else {
        this.$confirm('是否修改当前推荐院校信息', '温馨提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 修改
          updateRecommendAcademyById(this.schoolsForm).then(res => {
            this.recommendDialog = false
            this.searchRecommendAcademyList()
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '操作已取消'
          })
        })
      }
    },

    // 搜索
    handleFilter() {
      this.listQuery.pageNo = 1
      this.searchRecommendAcademyList()
    },
    // 根据院校名称查询 投放高中 list集合
    getHighSchoolOptions(title) {
      if (title) this.GetHighSchoolsByTitleOptions(title)
    },
    GetHighSchoolsByTitleOptions(title) {
      const params = {
        title: title
      }
      getSchoolsByTitle(params).then(response => {
        this.highSchoolsByTitleOptions = response.data
      })
    },
    // 根据院校名称查询 推荐院校 list集合
    getCollegeOptions(title) {
      if (title) this.GetCollegesByTitleOptions(title)
    },
    GetCollegesByTitleOptions(title) {
      const params = {
        academyName: title
      }
      queryLikeSchoolByName(params).then(response => {
        this.collegeByTitleOptions = response.data
      })
    },

    // 点击'新增'按钮
    handleAddNewRecommend() {
      this.action = 'new'
      this.recommendDialog = true
    },

    handleRadioChange(value) {
      if (value == '全国') {
        this.schoolsForm.isNationwide = 1
      } else {
        this.schoolsForm.isNationwide = 0
      }
      this.putInArea = []
      this.schoolsForm.schoolId = null
    },

    // 点击'编辑'按钮
    handleEditData(id) {
      queryRecommendAcademyInfoById(id).then(res => {
        const data = res.data
        this.action = 'modify'
        this.recommendDialog = true
        this.academyName = data.academyName
        this.schoolName = data.title
        this.schoolsForm.academyCode = data.academyCode
        this.schoolsForm.isNationwide = data.isNationwide
        this.schoolsForm.schoolId = data.schoolId
        this.schoolsForm.id = data.id
        this.schoolsForm.sort = data.sort
        if (data.provinceId) this.putInArea.push(data.provinceId)
        if (data.cityId) this.putInArea.push(data.cityId)
        if (data.regionId) this.putInArea.push(data.regionId)
        if (data.isNationwide == 1) {
          this.putInType = '全国'
        } else if (data.title) {
          this.putInType = '学校'
        } else {
          this.putInType = '地区'
        }
      })
    },

    handleDeleteData(id) {
      this.$confirm('是否确认将该院校从推荐列表中删除？', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteRecommendAcademyById(id).then(res => {
          if (res.message == '操作成功') {
            this.$message({
              message: res.message,
              type: 'success'
            })
          } else {
            this.$message({
              message: res.message,
              type: 'error'
            })
          }
          this.listQuery.pageNo = 1
          this.searchRecommendAcademyList()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '操作已取消'
        })
      })
    },

    // 关闭模态框时触发的事件
    dialogClosed() {
      this.recommendDialog = false
      this.putInArea = []
      this.academyName = ''
      this.schoolName = ''
      this.putInType = '地区'
      // 初始化数据
      this.schoolsForm = {
        sort: 100,
        provinceId: null,
        cityId: null,
        regionId: null,
        schoolId: null,
        isNationwide: null,
        academyCode: null,
        id: null
      }
    }

  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .create_model {
    width: 800px;
    margin: 0 auto;
  }
  .el-row {
    margin-bottom: 25px;
  }
  .pagination-container{
    margin-top:30px;
  }
</style>
